<template>
  <div class="menu">
    <el-card class="box-card">
      <el-tree
        :data="treeData"
        show-checkbox
        node-key="id"
        ref="tree"
        :default-expanded-keys="expandedKeys"
        :default-checked-keys="checkedKeys"
        :props="defaultProps">
      </el-tree>

      <el-button type="primary" @click="getCheckedNodes">提交</el-button>
      <el-button @click="reset">重置</el-button>
    </el-card>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { getRoleResources, allocateRoleResources } from '@/services/resource'
import { Tree } from 'element-ui'
export default Vue.extend({
  name: 'AllocResourcesIndex',
  data () {
    return {
      checkedKeys: [0],
      treeData: [],
      expandedKeys: [0],
      defaultProps: {
        children: 'resourceList',
        label: 'name'
      }

    }
  },
  created () {
    this.loadMenu(this.$route.query.roleId as string || -1)
  },
  methods: {
    async loadMenu (id: number | string) {
      const { data } = await getRoleResources(id)
      this.checkedKeys = []
      this.expandedKeys = []
      this.handleTree(data.data)
      this.treeData = data.data
    },
    handleTree (data: any) {
      if (!data) return null
      data.map((item: any) => {
        if (item.selected) {
          this.checkedKeys.push(item.id)
        }
        if (item.parentId === -1) {
          this.expandedKeys.push(item.id)
        }
        this.handleTree(item.subMenuList)
      })
    },
    reset () {
      (this.$refs.tree as Tree).setCheckedKeys([])
    },
    async getCheckedNodes () {
      this.$confirm('确认分配？', '分配提示', {})
        .then(async () => {
          const resourceIdList = (this.$refs.tree as Tree).getCheckedNodes().map(item => {
            return item.id
          })
          const { data } = await allocateRoleResources({
            roleId: Number(this.$route.query.roleId),
            resourceIdList
          })
          if (data.code === '000000') {
            this.$router.back()
            this.$message.success('提交成功')
          }
        })
        .catch((err) => {
          console.log(err)
          this.$message.info('已取消分配')
        })
    }
  }
})
</script>

<style lang="scss" scoped>
</style>
